<template>
  <div class="no-background-container">
    <el-affix :offset="0">
      <div class="qs-y-table-header">
        <div class="header-label">
          <div class="header-label-title flex items-center gap-2" style="margin-bottom: 0px">
            {{ routeName }}

            <div class="statistics-container flex-1">
              <div class="stat-item">
                <span class="stat-label">应签:</span>
                <span class="stat-value">{{ totalCount.应签 }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">实签:</span>
                <span class="stat-value">{{ totalCount.实签 }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">待签:</span>
                <span class="stat-value">{{ totalCount.待签 }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">请假:</span>
                <span class="stat-value">{{ totalCount.请假 }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="header-query">
          <div class="header-query-buttons">
            <el-button type="primary" @click="fetchData">刷新</el-button>
            <el-button type="primary" @click="showBatchSignIn = true">批量签到</el-button>
            <el-button :loading="exporting" type="success" @click="handleExport">
              <template #icon>
                <el-icon><download /></el-icon>
              </template>
              导出签到记录
            </el-button>
          </div>
          <query-form-component
            :list-loading="listLoading"
            :query-form="queryForm"
            :search-params="searchParams()"
            @submit="queryData"
            @update:query-form="updateQueryForm"
          />
        </div>
      </div>
    </el-affix>

    <sign-in-table
      :finally-columns="finallyColumns"
      :layout="layout"
      :list="list"
      :list-loading="listLoading"
      :query-form="queryForm"
      :total="total"
      @handle-current-change="handleCurrentChange"
      @handle-size-change="handleSizeChange"
      @sign-in="handleSignIn"
      @update:query-form="updateQueryForm"
    >
      <template #hotelCheckinInfo="{ row }">
        <div v-if="row.hotelCheckinInfo && row.hotelCheckinInfo.length > 0">
          <el-tag
            v-for="(item, index) in row.hotelCheckinInfo"
            :key="index"
            effect="light"
            style="margin-right: 5px"
            :type="item.checkinStatus ? 'success' : 'warning'"
          >
            <i-ep-house />
            {{ item.checkinStatus ? '住宿已签到' : '住宿未签到' }} (房间: {{ item.houseNumber }})
          </el-tag>
        </div>
        <span v-else>-</span>
      </template>
    </sign-in-table>

    <batch-sign-in-dialog v-model="showBatchSignIn" @refresh="fetchData" />
  </div>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import { computed, onActivated, onBeforeMount, ref } from 'vue'
import { useRoute } from 'vue-router'
import BatchSignInDialog from './components/BatchSignInDialog.vue'
import SignInTable from './components/SignInTable.vue'
import { moduleApi, searchParams, tableColumns } from './config'
import type { ApiResponse, Person, QueryForm } from './types'
import Public from '/@/api/public'

// 状态管理
const showBatchSignIn = ref(false)
const list = ref<Person[]>([])
const listLoading = ref(true)
const layout = ref('total, sizes, prev, pager, next, jumper')
const total = ref(0)
const queryForm = ref<QueryForm>({
  page: 1,
  limit: 20,
})

// 路由相关
const route = useRoute()
const routeName = computed(() => route.meta.title || '')

// 计算属性
const finallyColumns = computed(() => tableColumns.value)
const totalCount = ref<{
  应签: number
  实签: number
  待签: number
  请假: number
}>({
  应签: 0,
  实签: 0,
  待签: 0,
  请假: 0,
})
// 数据操作方法
const fetchData = async () => {
  listLoading.value = true
  try {
    const response = await Public.getDetailApi({ url: moduleApi, params: queryForm.value })
    const { code, result } = response as unknown as ApiResponse<{
      人员列表数据: { rows: Person[]; count: number }
      应签数: number
      签到数: number
      待签数: number
      请假数: number
    }>
    if (code === 0) {
      list.value = result.人员列表数据.rows
      total.value = result.人员列表数据.count
      totalCount.value.应签 = result.应签数
      totalCount.value.实签 = result.签到数
      totalCount.value.待签 = result.待签数
      totalCount.value.请假 = result.请假数
    }
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    listLoading.value = false
  }
}

const handleSignIn = async (userId: string) => {
  try {
    const activityId = localStorage.getItem('hongyouActId')
    await Public.signInApi({
      url: '/api/checkins',
      data: { userId, activityId },
    })
    ElMessage.success('签到成功!')
    fetchData()
  } catch (error) {
    console.error('签到失败:', error)
    ElMessage.error('签到失败')
  }
}

// 分页操作
const updateQueryForm = (newQueryForm: QueryForm) => {
  queryForm.value = { ...newQueryForm }
}

const handleSizeChange = (value: number) => {
  updatePagination({ page: 1, limit: value })
}

const handleCurrentChange = (value: number) => {
  updatePagination({ page: value })
}

const updatePagination = (params: Partial<QueryForm>) => {
  Object.assign(queryForm.value, params)
  fetchData()
}

const queryData = () => {
  updatePagination({ page: 1 })
}

// 初始化
const initialize = () => {
  const activityId = localStorage.getItem('hongyouActId')
  if (activityId) {
    queryForm.value.activityId = activityId
  }
  fetchData()
}

// 生命周期钩子
onBeforeMount(() => {
  initialize()
})

onActivated(() => {
  fetchData()
})

// 导出相关
const exporting = ref(false)

// 导出功能
const handleExport = async () => {
  const activityId = localStorage.getItem('hongyouActId')
  if (!activityId) {
    ElMessage.error('未找到活动ID')
    return
  }

  exporting.value = true
  try {
    // 第一步：获取文件路径
    const response = (await Public.exportApi({
      url: '/api/player/export',
      data: { activityId },
    })) as unknown as ApiResponse<string>

    console.log('1. 导出接口返回：', response)
    console.log('2. 原始文件路径：', response.result)

    if (response.code === 0 && response.result) {
      // 第二步：下载文件
      const baseUrl = import.meta.env.VITE_APP_BASE_URL || ''
      console.log('3. 基础URL：', baseUrl)

      // 移除返回路径中的 public 前缀（如果有）
      // const filePath = response.result.startsWith('public/') ? response.result.substring(7) : response.result
      // console.log('4. 处理后的文件路径：', filePath)

      const fileUrl = `${baseUrl}/${response.result}`
      console.log('5. 最终下载地址：', fileUrl)

      // 使用 window.open 打开下载链接
      window.open(fileUrl, '_blank')
      ElMessage.success('导出成功')
    } else {
      ElMessage.error('导出失败：未获取到文件路径')
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    exporting.value = false
  }
}
</script>

<style scoped>
.content-container {
  padding: 20px;
}

.header-query {
  display: flex;
  gap: 16px;
  align-items: center;
}

.header-query-buttons {
  display: flex;
  gap: 8px;
}

/* 统计信息样式 */
.statistics-container {
  display: flex;
  flex-wrap: wrap;
  padding: 0px 12px;
  background-color: rgba(0, 0, 0, 0.02);
  border-radius: 6px;
}

.stat-item {
  display: flex;
  align-items: center;
  padding: 4px 0;
  margin-right: 20px;
}

.stat-label {
  margin-right: 6px;
  font-size: 13px;
  color: var(--el-text-color-secondary);
}

.stat-value {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-color-primary);
}
</style>
